#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "network.h"

#define PORT 4444

#define ROOMS_REQUEST 1
#define BOOK_REQUEST 2
#define GUESTS_REQUEST 3

#define MAX_ERROR_MESSAGE_LENGTH 1024
#define MAX_NAME_LENGTH 1024

void print_info()
{
  printf("Usage:\n");
  printf("  hotelgwclient\n");
  printf("  hotelgwclient list <hostname>\n");
  printf("  hotelgwclient book <hostname> <type> '<guest name>'\n");
  printf("  hotelgwclient guests <hostname> \n");
}

void list(char * host_name)
{
  int id, nfree, price, i,n, type = htonl(ROOMS_REQUEST);
  int socket = socket_open(host_name, PORT);
  error_if(write(socket, &type, sizeof(int)) != 4, "Bad write");
  error_if(read(socket, &n, sizeof(int)) != 4, "Bad read");
  n = ntohl(n);
//  printf("%d room types\n", n);
  for (i = 0; i < n; i++) {
    int r1 = read(socket, &id, sizeof(int));
    int r2 = read(socket, &nfree, sizeof(int));
    int r3 = read(socket, &price, sizeof(int));
    error_if(r1 != 4 || r2 != 4 || r3 != 4, "Bad read");
    printf("%d rooms of type %d at %d euros per night\n", ntohl(nfree), ntohl(id), ntohl(price));
  }
  close(socket);
}

void book(char * host_name, char * room_type, char * name)
{
  int room_id = htonl(atoi(room_type));
  int len = htonl(strlen(name));
  int type = ntohl(BOOK_REQUEST);
  int socket = socket_open(host_name, PORT);
  error_if(write(socket, &type, sizeof(int)) != sizeof(int), "Bad write");
  error_if(write(socket, &room_id, sizeof(int)) != sizeof(int), "Bad write");
  error_if(write(socket, &len, sizeof(int)) != sizeof(int), "Bad write");
  error_if(write(socket, name, strlen(name)) != strlen(name), "Bad write");
  error_if(read(socket, &len, sizeof(int)) != sizeof(int), "Bad read");
  len = ntohl(len);
  if (len > 0) {
    char buffer[MAX_ERROR_MESSAGE_LENGTH];
    if (len > MAX_ERROR_MESSAGE_LENGTH) {
      len = MAX_ERROR_MESSAGE_LENGTH - 1;
    }
    error_if(read(socket, buffer, len) != len, "Bad read");
    buffer[len] = 0;
    printf("Error: %s\n", buffer);
  }
  close(socket);
}

void guests(char * host_name)
{
  int i, n, len;
  char buffer[MAX_NAME_LENGTH];
  int type = ntohl(GUESTS_REQUEST);
  int socket = socket_open(host_name, PORT);
  error_if(write(socket, &type, sizeof(int)) != 4, "Bad write");
  error_if(read(socket, &n, sizeof(int)) != sizeof(int), "Bad read");
  n = ntohl(n);
  for (i = 0; i < n; i++) {
    error_if(read(socket, &len, sizeof(int)) != 4, "Bad read");
    len = ntohl(len);
    error_if(read(socket, buffer, len) != len, "Bad read");
    buffer[len] = 0;    
    printf("%d. %s\n", i+1, buffer);
  }
  close(socket);  
}

int main(int argi, char * argv[])
{
  if (argi == 3 && strcmp(argv[1], "list") == 0) {
    list(argv[2]);
  } else if (argi == 5 && strcmp(argv[1], "book") == 0) {
    book(argv[2], argv[3], argv[4]);
  } else if (argi == 3 && strcmp(argv[1], "guests") == 0) {
    guests(argv[2]);
  } else {
    print_info();
  }
  return 0;
}
